package algo;

import model.tsp.Problem;
import model.tsp.Solution;
import plot.TSPPanel;

import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.Random;

public abstract class HeuristicSearch {

    protected Problem problem;
    protected final int[][] distance;

    protected Random random = new Random();

    public HeuristicSearch(Problem problem) {
        this.problem = problem;
        this.distance = problem.getDistance();
        random.setSeed(123);
    }

    // 计算目标值
    public int calculateFitness(List<Integer> permutation) {
        int dist = 0;
        int len = permutation.size();
        for (int i = 0; i < len - 1; i++) {
            dist += distance[permutation.get(i)][permutation.get(i + 1)];
        }
        dist += distance[permutation.get(len - 1)][permutation.get(0)];
        return dist;
    }

    public abstract void solve();

    // 绘制路径
    protected void plot(Solution solution) {
        try {
            TSPPanel panel = new TSPPanel(problem);
            panel.displayTour(solution, Color.BLACK, new BasicStroke(2.0f));

            JFrame frame = new JFrame();
            frame.getContentPane().setLayout(new BorderLayout());
            frame.getContentPane().add(panel, BorderLayout.CENTER);
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setSize(500, 400);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);

            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
